#include "audio.h"


//==============================================================================DATA
#if 0
typedef struct codec{
	void *handle;
	int (*parser)( entry_s *ety );
	int (*decoder)( entry_s *ety );
}codec_s;
#endif
static codec_s hold[LIB_MAX];


static int codec_install( char *codec_name, codec_s *c );
static void codec_uninstall();
//==============================================================================FUNCTION
int plugin_codec_install()
{
	int i=0;
	bzero( hold, sizeof(hold) );
	
	for( i=0 ; context.libs_codec[i] != NULL ; i++ ){
		codec_install( context.libs_codec[i], hold+i );
	}
	
	return EXIT_SUCCESS;
}

void plugin_codec_uninstall()
{
	int i;
	for( i=0 ; i < LIB_MAX ; i++ ){
		codec_uninstall( hold+i );
	}
}

//------------------------------------------------------------------------------
static int codec_install( char *codec_name, codec_s *cs )
{
	void *handle = NULL, *func = NULL;

	char _codec_name[512] = "\0";
	strcpy( _codec_name, context.lib_dir);
	strcat( _codec_name, codec_name );
	
	handle = dlopen ( _codec_name, RTLD_NOW | RTLD_GLOBAL);
	if( handle ) cs->handle = handle;
	else goto error;

	func = dlsym( handle, "parser" );
	if( NULL == func ) goto error;
	else cs->parser = func;
	func = NULL;

	func = dlsym( handle, "decoder" );
	if( NULL == func ) goto error;
	else cs->decoder = func;

	return EXIT_SUCCESS;
	
error:
	fprintf( stderr, "ERROR: %s", dlerror() );
	cs->handle = NULL;
	return EXIT_FAILURE;
}

static void codec_uninstall( codec_s *cs )
{
	if( cs == NULL ) return;
	if( cs->handle ) dlclose( cs->handle );
}

//------------------------------------------------------------------------------
int parser_solution( entry_s *ety )
{
	int i, r;

	for( i=0 ; i < LIB_MAX ; i++ ){
		if( hold[i].handle == NULL ) continue;
		else r = hold[i].parser(ety);
		if(r == EXIT_SUCCESS) break;
	}
	
	return r;
}

int decoder_solution( entry_s *ety )
{
	int i, r;

	for( i=0 ; i < LIB_MAX ; i++ ){
		if( hold[i].handle == NULL ) continue;
		else r = hold[i].decoder(ety);
		if(r == EXIT_SUCCESS) break;
	}

	return r;
}





